let utils = require("../../../utils/util.js")
// 获取应用实例
const app = getApp()
//const feedListUrl = 'http://api.xitu.io/resources/gold?category=frontend&limit=30&offset=30&order=heat'
//const feedListUrl = 'https://recommender-api-ms.juejin.im/v1/get_recommended_entry?suid=B32RRI3UmJI6Vv3JEvUM&ab=welcome_3&src=web';
const feedListUrl = 'https://bukaa.cn/api-cms/juejin/find?size=8&channel=weapp';
const feedDetailUrl = 'https://bukaa.cn/api-cms/juejin/detail/';

Page({
  // 页面数据
  data: {
    tipsText: '掘金，一个帮助开发者成长的社区',
    loading: false,
    canLoadMore: true,
    feedPage: 1,    
    feedList: [],
    show: true
  },

  // 页面初始化后
  onLoad: function () {
    console.log('Index Page On Load')
    wx.showNavigationBarLoading()
    this.data.feedPage = 1
    this.getFeedList()
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    var self = this
    wx.showNavigationBarLoading()
    setTimeout(function () {
      self.data.canLoadMore = true
      self.data.feedPage = 1
      self.getFeedList()
    }, 500);
  },

  // 底部加载
  onReachBottom: function () {
    var self = this
    if (!self.data.canLoadMore) {
      // 不能加载更多，直接返回
      return;
    }
    wx.showNavigationBarLoading()
    setTimeout(function () {
      self.getFeedList()
    }, 500);
  },

  getFeedList: function () {
    var self = this

    if (self.data.loading) {
      // 正在加载中，直接返回
      return;
    }

    if (!self.data.canLoadMore) {
      // 不能加载更多，直接返回
      self.closeLoadingView()
      return;
    }

    // 标记正在加载中
    self.setData({loading: true});

    debugger;

    wx.request({
      url: feedListUrl + '&page=' + self.data.feedPage,
      method: 'GET',
      data: {},
      success: function (result) {
        console.log('Feed list request success', result.data)
        var data = result.data;
        if (data.status === 'ok') { // 接口请求成功
          var feeds = data.data.list;
          if (feeds && feeds.length > 0) { // 如果有返回数据
            feeds.forEach(function(feed){
              try{
                feed['postdate'] = utils.getDateDiff(utils.formatTime(new Date(feed['updatedAt'])));
                feed['author'] = JSON.parse(feed['user'])['username'];
                feed['avatar'] = JSON.parse(feed['user'])['avatarLarge'];
              }catch(e){
                console.log(e.stack);
              }
            });
            
            feeds = feeds.filter(function(feed){
              if (feed.originalUrl.indexOf("juejin.im") != -1){
                return true;
              }
              return false;
            });
            var newFeedPage = self.data.feedPage + 1;
            var newFeedList = []
            if (self.data.feedPage > 1) {
              newFeedList = newFeedList.concat(self.data.feedList)
            }
            newFeedList = newFeedList.concat(feeds);
            
            self.setData({
              feedPage: newFeedPage,
              feedList: newFeedList
            })
          } else {
            self.setData({ loading: false });
            // 标记不能加载更多了
            // self.data.canLoadMore = false
            // wx.showToast({
            //   icon: 'none',
            //   title: '总共有 ' + self.data.feedList.length + ' 条文章，没有更多了'
            // })
          }
        }
      },
      fail: function (errMsg) {
        console.log('Feed list request fail', errMsg)
      },
      complete: function () {
        // 标记加载结束
        self.setData({ loading: false });
        self.closeLoadingView()
      }
    })
  },

  closeLoadingView: function () {
    wx.hideNavigationBarLoading()
    wx.stopPullDownRefresh()
  },

  // 列表项点击
  feedItemClick: function (event) {
    var feed = event.currentTarget.dataset.feed
    if (feed && feed.id) {
      wx.navigateTo({
        url: './detail/detail?id=' + feed.id
      })
    }
  },

  // 搜索按钮点击
  searchBtnClick: function (event) {
    wx.navigateTo({
      url: '../search/search'
    })
  },

  // 转发
  onShareAppMessage: function (res) {
    var self = this
    return {
      title: '专注于知识分享',
      path: 'pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onShow: function () {
    this.setData({show:true});
  },
  onHide: function () {
    this.setData({ show: false });
  },

})
